/**
 * 数据上传
 * Created by WMM on 2018/06/18.
 */
import { Component } from '@angular/core';
import {
  IonicPage,
  NavController,
  ToastController,
  NavParams,
  AlertController,
  LoadingController
} from 'ionic-angular';
import { LoginApi } from '../../api/login/LoginApi';
import { AddressApi } from "../../api/login/AddressApi";
import { OfflineDataApi } from "../../api/offline-data/OfflineDataApi";
import { BarcodeScanner } from '@ionic-native/barcode-scanner';


@IonicPage()
@Component({
  selector: 'page-data-upload',
  templateUrl: 'data-upload.html'
})
export class DataUpload {

  private LeaveTag: boolean = true;
  private user: object;
  private loadOrUnloadList: Array<any>;
  private ruleRecordList: Array<any>;
  private exceptionInfoList: Array<any>;
  private userName: string;
  private pwd: string;
  private logininfo: string[];
  private useronlie: boolean = false;

  private pageOneTag: boolean = false;
  private pageTwoTag: boolean = false;
  private uploadBtnTag: boolean = true;
  private projectInfoTag: boolean = true;

  private projectId: string;
  private planId: string;
  private positionId: string;
  private projectName: string;
  private planName: string;
  private positionName: string;


  private project: Array<any>;
  private plan: Array<any>;
  private position: Array<any>;

  private projectshow: Array<any>;
  private planshow: Array<any>;
  private positionshow: Array<any>;


  // 页面离开时调用
  ionViewWillUnload() {
    if (this.useronlie) {
      const http$ = this.loginApi.out(this.userName);
      http$.subscribe((val: any) => {
        let res = JSON.parse(val);
        if (res.state) {
          localStorage.removeItem("token");
          localStorage.removeItem("userInfo");
        }
      });
    }
  }

 //  离开页面守卫
  ionViewCanLeave(): boolean {
    return this.LeaveTag;
  }


  constructor(private offlineDataApi: OfflineDataApi, private addressApi: AddressApi, public loginApi: LoginApi, public navCtrl: NavController, private loadingCtrl: LoadingController, private barcodeScanner: BarcodeScanner, private alertCtrl: AlertController, public params: NavParams, private toastCtrl: ToastController) {
    this.loadOrUnloadList = params.get("loadOrUnloadList");
    this.ruleRecordList = params.get("ruleRecordList");
    this.exceptionInfoList = params.get("exceptionInfoList");
    this.projectName = "";
    this.planName = "";
    this.positionName = "";
    this.projectshow = [];
    this.planshow = [];
    this.positionshow = [];
    this.user = {
      name: "",
      company: ""
    }
  }


  doLogin() {
    const http$ = this.loginApi.auth(this.userName, this.pwd);
    http$.subscribe((val: any) => {
      let loginResult = JSON.parse(val);
      if (loginResult.state) {
        this.useronlie = true;
        this.showMsg("登陆成功,正在获取所有参与的项目信息...");
        localStorage.setItem("token", loginResult.token);
        localStorage.setItem("userInfo", loginResult.userInfo);
        this.offlineDataApi.getAppUserInfo().subscribe(res => {
          this.user = res;
          this.pageOneTag = true;
          this.offlineDataApi.getAppProjectInfo().subscribe(res => {
            if (res.state) {
              this.project = res.data.project;
              this.plan = res.data.plan;
              this.position = res.data.position;
              this.project.forEach(i => {
                let item: object = {
                  id: i.id,
                  name: i.projectName
                }
                this.projectshow.push(item);
              });
              this.showMsg("信息获取完成！");
            } else {
              this.showMsg(res.msg);
              this.useronlie = false;
            }
          });
        });
      } else {
        this.showMsg(loginResult.msg);
        localStorage.removeItem("token");
        localStorage.removeItem("userInfo");
      }
    });
  }


  scanLogin() {
    this.barcodeScanner.scan({ showTorchButton: true, resultDisplayDuration: 0 }).then((data) => {
      if (data.text.length != 0) {
        this.logininfo = data.text.split("丨");
        if (this.logininfo.length == 2) {
          this.userName = this.logininfo[0];
          this.pwd = this.logininfo[1];
          this.doLogin();
        } else {
          this.showMsg("请扫描正确的二维码!");
        }
      } else {
        this.fixshowMsg("请扫描正确的二维码!");
      }
    }, (err) => {
      this.showMsg("扫描出现异常" + err);
    });
  }


  switchUser() {
    this.useronlie = false;
    const http$ = this.loginApi.out(this.userName);
    http$.subscribe((val: any) => {
      let res = JSON.parse(val);
      if (res.state) {
        this.pageOneTag = false;
        this.projectInfoTag = true;
        this.userName = "";
        this.pwd = "";
        this.projectName = "";
        this.planName = "";
        this.positionName = "";
        this.projectshow = [];
        this.planshow = [];
        this.positionshow = [];
        this.projectId = "";
        this.planId = "";
        this.positionId = "";
        localStorage.removeItem("token");
        localStorage.removeItem("userInfo");
      } else {
        this.showMsg("系统出错,请重试!");
      }
    });
  }


  goOnline() {
    if (this.useronlie) {
      let alert = this.alertCtrl.create({
        title: '使用在线功能请确保网络通畅!',
        message: "点击确定进行GPS选择位置!",
        buttons: ['取消',
          {
            text: '确定',
            handler: data => {
              this.gpsAddress();
            }
          }]
      });
      alert.present();
    } else {
      this.showMsg("请先登陆!");
    }

  }

  /**
   * 进行gps定位，去服务器获取最近的位置列表供用户选择
   */
  gpsAddress() {
    var options = {
      enableHighAccuracy: true,  // 是否使用 GPS
      maximumAge: 60000,         // 缓存时间
      timeout: 27000,            // 超时时间
      coorType: 'bd09ll'         // 默认是 gcj02，可填 bd09ll 以获取百度经纬度用于访问百度 API
    }
    navigator.geolocation.getCurrentPosition((position: any) => {
      if (<string>position.coords.latitude == "5e-324" || <string>position.coords.longitude == "5e-324" || <string>position.coords.latitude == "4.9E-324" || <string>position.coords.longitude == "4.9E-324") {
        const alert = this.alertCtrl.create({
          title: '定位失败!，请检查位置功能与权限是否打开！',
          subTitle: '位置功能》》设置-位置-开启  位置权限》》设置-权限-应用-定位—开启',
          buttons: ['确定']
        });
        alert.present();
        return;
      }
      this.addressApi.getAddress(<string>position.coords.latitude, <string>position.coords.longitude).subscribe(res => {
        let result = JSON.parse(res);
        if (result.state) {
          this.showMsg("定位成功,正在链接服务器获取最近位置信息...");
          let addresses = result.data;
          this.doSelectAddress(addresses);
        } else {
          /**
           * 登陆成功,10公里范围内未查询到位置信息
           */
          //this.showMsg("定位成功,"+result.msg);
        }
      });
    }, (error: any) => {
      this.showMsg(error);
    }, options);
  }

  /**
   * 用户进行位置选择，选择完毕后进入下一个页面：项目计划列表页。
   * @param {object[]} addresses
   */
  doSelectAddress(addresses: object[]) {
    let alert = this.alertCtrl.create();

    alert.setTitle('请选择您所在的位置');
    for (var index in addresses) {
      let item: any = addresses[index];
      alert.addInput({
        type: 'radio',
        label: item.positionName,
        value: item.id,
        checked: parseInt(index) == 0 ? true : false
      });
    }
    alert.addButton({
      text: '确定',
      handler: (data: any) => {
        this.navCtrl.setRoot('ProjectPlan', { "position": data, "userName": this.userName }, {
          animate: true,
          direction: 'forward'
        });
      }
    });
    alert.present();
  }


  //点击取消返回
  goBack() {
    this.navCtrl.pop();
  }

  showMsg(msg: string) {
    var toast = this.toastCtrl.create({
      message: msg,
      duration: 3000,
      position: 'bottom'
    });
    toast.present();
  }

  fixshowMsg(msg: string) {
    this.LeaveTag = false;
    var toast = this.toastCtrl.create({
      message: msg,
      duration: 3000,
      position: 'bottom'
    });
    toast.present();
    setTimeout(() => this.LeaveTag = true, 1000);
  }



  selectChange(type: string, id: any) {
    if (type == "project") {
      this.planshow = [];
      this.positionshow = [];
      this.plan.forEach(i => {
        if (i.projectId == id) {
          let item: object = {
            id: i.id,
            name: i.planCode
          }
          this.planshow.push(item);
        }
      });
    } else if (type == "plan") {
      this.positionshow = [];
      this.position.forEach(i => {
        if (i.planId == id) {
          let item: object = {
            id: i.id,
            name: i.addressName
          }
          this.positionshow.push(item);
        }
      });
    } else if (type == "position") {
      // console.log(event);
    } else {
      this.showMsg("参数错误，请重试！");
    }
  }

  confirmProject() {
    if (this.projectId == undefined || this.projectId == null || this.projectId == "") {
      this.showMsg("请先选择项目！");
      return;
    }
    if (this.planId == undefined || this.planId == null || this.planId == "") {
      this.showMsg("请先选择计划！");
      return;
    }
    if (this.positionId == undefined || this.positionId == null || this.positionId == "") {
      this.showMsg("请先选择地点！");
      return;
    }

    let element1 = this.projectshow.find((item) => {
      if (item.id == this.projectId) {
        return item;
      }
    })
    this.projectName = element1.name;

    let element2 = this.planshow.find((item) => {
      if (item.id == this.planId) {
        return item;
      }
    })
    this.planName = element2.name;

    let element3 = this.positionshow.find((item) => {
      if (item.id == this.positionId) {
        return item;
      }
    })
    this.positionName = element3.name;

    this.projectInfoTag = false;
    this.pageTwoTag = true;
    this.uploadBtnTag = false;
  }

  switchPorject() {
    this.uploadBtnTag = true;
    this.projectInfoTag = true;
    this.pageTwoTag = false;
    this.projectName = "";
    this.planName = "";
    this.positionName = "";
  }

  dataUpload() {
    let loader = this.loadingCtrl.create({
      content: "正在上传...",
    });
    loader.present();
    //拼装数据
    let otherInfo = {
      project: this.projectshow.filter(item => item.id === this.projectId)[0],
      plan: this.planshow.filter(item => item.id === this.planId)[0],
      position: this.positionshow.filter(item => item.id === this.positionId)[0],
    }
    let data = {
      loadOrUnloadList: this.loadOrUnloadList,
      ruleRecordList: this.ruleRecordList,
      exceptionInfoList: this.exceptionInfoList,
      otherInfo: otherInfo
    };
    const http$ = this.offlineDataApi.dataUpload(JSON.stringify(data));
    http$.subscribe((val: any) => {
      loader.dismiss();
      let scanResult = JSON.parse(val);
      if (scanResult.state) {
        this.showMsg('上传成功');
      } else {
        this.showMsg('上传失败');
      }
    });

  }

  cutImageBase64(base64: string, width: string, height: string, callback) {
    let newbase64: string;
    if (base64 == "assets/imgs/photo.jpg" || base64 == "") {
      newbase64 = "assets/imgs/photo.jpg";
      callback ? callback(newbase64) : null; //调用回调函数
    } else {
      let _img = new Image();
      _img.src = base64;
      _img.onload = function () {
        let _canvas = document.createElement("canvas");
        _canvas.setAttribute("width", width);
        _canvas.setAttribute("height", height);
        _canvas.getContext("2d").drawImage(_img, 0, 0, Number(width), Number(height));
        newbase64 = _canvas.toDataURL("image/jpeg");
        callback ? callback(newbase64) : null; //调用回调函数
      }
    }
  }

}
